package com.zeedev.flyingsaucer.modules.FileModule;

import android.os.Environment;
import com.google.inject.Inject;

import java.io.*;

public class AndroidFileLink implements FileLink {

    @Inject
    public AndroidFileLink() {


    }

    @Override
    public File copyFile(File inputFile, File outputFile) throws IOException, SecurityException {
        if (!isWriteable()) {
            throw new IOException("Could not mount external media.");
        }

        boolean createdFileSuccess = outputFile.createNewFile();
        if (createdFileSuccess == false) {
            throw new IOException("Error creating file.");
        }

        FileInputStream fis = new FileInputStream(inputFile);
        BufferedInputStream bis = new BufferedInputStream(fis, 2048);

        FileOutputStream fos = new FileOutputStream(outputFile);
        BufferedOutputStream bos = new BufferedOutputStream(fos, 2048);

        int size = (int) inputFile.length();
        byte[] byteArr = new byte[size];
        int read = bis.read(byteArr);
        bos.write(byteArr);

        fis.close();
        fos.close();

        if (read != size) {
            throw new IOException("File size and actual file size are different.");
        }

        return outputFile;

    }

    @Override
    public Boolean isReadable() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) || Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY);
    }

    @Override
    public Boolean isWriteable() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    @Override
    public Boolean hasExternalFile(File file) throws SecurityException, IOException {
        if (!isReadable()) {
            throw new IOException("Could not mount external media.");
        }
        boolean ret = false;
        if (file != null) {
            ret = file.exists();
        }
        return ret;
    }

}
